package pl;

import java.util.Map;
import javax.persistence.*;
import org.apache.openjpa.persistence.OpenJPAEntityManager;
import org.apache.openjpa.persistence.OpenJPAPersistence;

public class ConexionBBDD {

    public EntityManagerFactory factory;
    private EntityManager em;
    public OpenJPAEntityManager kem;

// *****************************************************************************

    @SuppressWarnings({ "unchecked", "rawtypes" })
	private Map getProperties() {
        Map properties = System.getProperties();
        properties.put("openjpa.ConnectionURL", "jdbc:postgresql://127.0.10.3:5432/practica13");
        properties.put("openjpa.ConnectionUserName", "postgres");
        properties.put("openjpa.ConnectionPassword", "1234");
        properties.put("openjpa.ConnectionDriverName", "org.postgresql.Driver");
        properties.put("openjpa.ConnectionFactoryProperties","PrettyPrint=true, PrettyPrintLineLength=80");
        return properties;
    }

    ConexionBBDD () throws BaseDatosException {
        try {
	        // System.out.println("Creamos el la factoria de EntityManagers con el nombre que le hemos dado a en la declaracion del xml persistence-unit name");
            factory = Persistence.createEntityManagerFactory("reversemappingtool", getProperties());
            
	        // System.out.println("createEntityManager: factory: " + factory);
            em = factory.createEntityManager();

	        // System.out.println("EntityManager: em: " + em);
            kem = OpenJPAPersistence.cast(em);
        }
        catch (Exception e) {
            System.err.println("Error al crear la sesion OpenJPA de base de datos." + e.getMessage());
            throw new BaseDatosException(e.getMessage());
        }
    }
    
    public void abrir() {
    	
    }

    public void cerrarConexion () {
        // System.out.println("[org.icaro.datos.DAO.ConexionBBDD.cerrarConexion] kem " + kem);
        if (kem != null) {
            kem.close();
	        // System.out.println("[org.icaro.datos.DAO.ConexionBBDD.cerrarConexion] kem CERRADO.");
        }

        // System.out.println("[org.icaro.datos.DAO.ConexionBBDD.cerrarConexion] factory " + factory);
        if (factory != null) {
            factory.close();
	        // System.out.println("[org.icaro.datos.DAO.ConexionBBDD.cerrarConexion] factory CERRADO.");
        }
    }
}
